/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import domain.Dia;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author Lacho
 */
public class daoDia {
    
     private Session sesion; 
    private Transaction tx;  

    public int guardaDia(Dia dia) throws HibernateException 
    { 
        int id = 0;  

        try 
        { 
            iniciaOperacion(); 
            id = (int) sesion.save(dia); 
            tx.commit(); 
        } catch (HibernateException he) 
        { 
            manejaExcepcion(he); 
            throw he; 
        } finally 
        { 
            sesion.close(); 
        }  

        return id; 
    }  

    public void actualizaDia(Dia dia) throws HibernateException 
    { 
        try 
        { 
            iniciaOperacion(); 
            sesion.update(dia); 
            tx.commit(); 
        } catch (HibernateException he) 
        { 
            manejaExcepcion(he); 
            throw he; 
        } finally 
        { 
            sesion.close(); 
        } 
    }  

    public void eliminaDia(Dia dia) throws HibernateException 
    { 
        try 
        { 
            iniciaOperacion(); 
            sesion.delete(dia); 
            tx.commit(); 
        } catch (HibernateException he) 
        { 
            manejaExcepcion(he); 
            throw he; 
        } finally 
        { 
            sesion.close(); 
        } 
    }  

    public Dia obtenDia(int idDia) throws HibernateException 
    { 
        Dia dia = null;  
        try 
        { 
            iniciaOperacion(); 
            dia = (Dia) sesion.get(Dia.class, idDia); 
        } finally 
        { 
            sesion.close(); 
        }  

        return dia; 
    }  

    public List<Dia> obtenListaDias() throws HibernateException 
    { 
        List<Dia> listaDias = null;  

        try 
        { 
            iniciaOperacion(); 
            listaDias = sesion.createQuery("from Dia").list(); 
        } finally 
        { 
            sesion.close(); 
        }  

        return listaDias; 
    }  

    private void iniciaOperacion() throws HibernateException 
    { 
        sesion = HibernateUtil.getSessionFactory().openSession(); 
        tx = sesion.beginTransaction(); 
        tx.begin();
    }  

    private void manejaExcepcion(HibernateException he) throws HibernateException 
    { 
        tx.rollback(); 
        throw new HibernateException("Ocurrió un error en la capa de acceso a datos", he); 
    }
}
